package qj.srt;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;

import qj.util.Cols;
import qj.util.DateUtil;
import qj.util.FileUtil;
import qj.util.IOUtil;
import qj.util.StringUtil;
import qj.util.funct.F1;
import qj.util.funct.P1;

public class SrtRepin {
	public static void main(String[] args) {
		SrtRepin srtRepin = new SrtRepin();
		
//		srtRepin.pin("01:42:05", diff("01:43:18,758", "01:42:39"));
//		srtRepin.pin("01:44:00", 121200);
		srtRepin.pin("01:42:00", diff("01:43:51,260", "01:44:57,260"));
		
		System.out.println(srtRepin.getCode());
		
		File dir = new File("/Users/quanle/Documents/Store/Films/Die.Hard.1988.DVDRip.XviD-UnSeeN");
		srtRepin.repin(
				new File(dir, "Die.Hard.1988.DVDRip.XviD-UnSeeNA.srt"), 
				new File(dir, "Die.Hard.1988.DVDRip.XviD-UnSeeN.srt")
				);
	}
	
	private String getCode() {
		StringBuilder sb = new StringBuilder();
		
		for (Pin pin : pins) {
			String time = DateUtil.format(new Date(pin.time), "HH:mm:ss");
			sb.append("srtRepin.pin(\"" + time + "\", " + pin.delay + ");\n");
		}
		return sb.toString();
	}

	private static int diff(String srtTime, String inMovieTime) {
		return (int) (-toTime(srtTime.substring(0, srtTime.indexOf(",")))
		+ toTime(inMovieTime)
		- Integer.parseInt(srtTime.substring(srtTime.indexOf(",") + 1)));
	}

	ArrayList<Pin> pins = new ArrayList<Pin>();
	private void pin(String timeSrt, int srtDelay) {
		long time = toTime(timeSrt);
		pins.add(new Pin(time, srtDelay));
	}
	
	static class Pin {
		long time;
		long delay;
		public Pin(long time, int delay) {
			this.time = time;
			this.delay = delay;
		}
		static F1<Pin, Long> getTime = new F1<Pin, Long>() {public Long e(Pin pin) {
			return pin.time;
		}};
	}

	private void repin(File from, File to) {
		to = decideTo(to);
		
		OutputStream out = FileUtil.fileOutputStream(to);
		FileInputStream in = FileUtil.fileInputStream(from);
		
		final P1<Srt> writer = Srt.writer(out);
		Srt.readSrt(in, new P1<Srt>() {public void e(Srt srt) {
			Pin pin = Cols.indexedBinaryGetLow(pins, Pin.getTime, srt.from);
			if (pin != null) {
				srt.from += pin.delay;
				srt.to += pin.delay;
			}
			writer.e(srt);
		}});
		
		IOUtil.closeAll(in, out);
	}

	private static File decideTo(File to) {
		for (int i = 0; ; i++) {
			File deciding;
			if (i != 0) {
				String path = to.getPath();
				int lastDot = path.lastIndexOf(".");
				deciding = new File(StringUtil.insert("" + i, lastDot, path));
			} else {
				deciding = to;
			}
			if (!deciding.exists()) {
				return deciding;
			}
		}
	}

	private static long toTime(String time) {
		int count = StringUtil.countHappens(':', time);
		String format = count==1 ? "mm:ss" : "HH:mm:ss";
		return DateUtil.parse(time, format).getTime();
	}
}
